package distributedbank.responses;

import java.io.IOException;
import java.util.HashMap;
import java.util.List;
import java.util.Map.Entry;
import distributedbank.client.ClientUI;
import distributedbank.requests.Request;
import distributedbank.requests.TransferDepositRequest;
import distributedbank.server.Account;

/**
 * SsResponse is the snapshot result sent from Server to GUI.
 */
public class SsResponse extends Response
{
    private static final long serialVersionUID = -233145107601057277L;

    private String ssInfo;

    private static final String ACCOUNT_FORMAT = "Account: %d, Balance: %s";
    /**
     * Response String Format:</br> "Account:" + accountNumber + ", Balance: " + balance
     * + "\n"</br> "Account:" + accountNumber + ", Balance: " + balance +
     * "\n"</br> ......</br> "Account:" + accountNumber + ", Balance: " +
     * balance + "\n"</br> "Transferring " + amount + " from " +
     * srcAccountNumber1 + " to " + DstAccountNumber + "\n"</br> "Transferring "
     * + amount + " from " + srcAccountNumber1 + " to " + DstAccountNumber +
     * "\n"</br> ......</br> "Transferring " + amount + " from " +
     * srcAccountNumber1 + " to " + DstAccountNumber + "\n"</br>
     */
    public SsResponse(int ssId, HashMap<Integer, Account> state, List<Request> channel ) {
        ssInfo = "\nThis Snapshot's ID is '" + ssId + "'.\n";
    	StringBuffer sb = new StringBuffer();
        for( Entry<Integer, Account> pair : state.entrySet() ) {
            sb.append( String.format( ACCOUNT_FORMAT, pair.getKey(), pair
                    .getValue().getBalanceInDollarsWithSign() ) );
            sb.append( "\n" );
        }
        for( Request r : channel ) {
            if( !(r instanceof TransferDepositRequest) ) {
                //never happens. r must be instance of TDR
                continue;
            }
            TransferDepositRequest tdr = (TransferDepositRequest) r;
            sb.append( tdr.getRequestInfo().toString() ).append( "\n" );
        }
        ssInfo += sb.toString();
        if(sb.toString().equals("")){
        	ssInfo += "Nothing is on this bank branch.\n";
        }
    }
    /**
     * Show snapshot information on a new frame. 
     */
    public void runResponse( ClientUI client ) throws IOException {
        client.setSsFrameVisible();
        client.addInfoToSs(ssInfo);
    }
}
